package com.laicunba.ext.web.controller.h5.activity;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.constant.GloabConstant;
import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.VcoinWalletDO;
import com.laicunba.pojo.vo.WeiXinVO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.PicService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.service.WeiXinService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.QRcodeUtil;
import com.laicunba.util.StringUtil;

/**
 * 2周年庆活动
 * 
 * @author lws
 *
 */
@Controller
@RequestMapping(value = "/h5/ext/activity")
public class AnniversaryActivityController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(AnniversaryActivityController.class);
	
	@Autowired
	private ActivityService activityService;
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private SlaveActivityJoinService slaveActivityJoinService;
	@Autowired
	private WeiXinService weiXinService;
	@Autowired
	private UserService userService;
	@Autowired
	private PicService picService;
	@Value("${ftp.dir:/resource/}")
	private String ftpDir;
	
	/**
	 * 访问2周年活动页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/anniverary_activity_go_invite.htm")
	public ModelAndView anniveraryActivityGoInvite(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("2nd_anniversary.jsp");
		try {
			UserDO user = getCurrentUser(request);
			ActivityDO activity = activityService.get(ActivityDO.class, "20170814lottery");
			if (activity == null || activity.getBeginTime().after(new Date())){
				view.addObject("lotteryActivityNoBegin", 1);
			}
			if(activity != null && activity.getEndTime().before(new Date())) {
				view.addObject("lotteryActivityEnd", 1);
			}
			
			ActivityDO openBoxActivity = activityService.get(ActivityDO.class, "20170814box");
			if (openBoxActivity == null || openBoxActivity.getBeginTime().after(new Date())){
				view.addObject("openBoxActivityNoBegin", 1);
			}
			if(openBoxActivity != null && openBoxActivity.getEndTime().before(new Date())) {
				view.addObject("openBoxActivityEnd", 1);
			}
			
			ActivityDO inviteActivity = activityService.get(ActivityDO.class, "20170807");
			if (inviteActivity == null || inviteActivity.getBeginTime().after(new Date())){
				view.addObject("inviteActivityNoBegin", 1);
			}
			if(inviteActivity != null && inviteActivity.getEndTime().before(new Date())) {
				view.addObject("inviteActivityEnd", 1);
			}
			
			if(user == null) {
				view.addObject("anniversaryLotteryChangeCount", 1);
				return view;
			} 
			// 获得积分
			String currentUserIsCleared = CacheUtil.getAttribute("act.anniversary.20170807activity." + user.getId() + ".clean-act20170703-vcoin");
			if (StringUtil.isEmpty(currentUserIsCleared) || !currentUserIsCleared.equals("1")) {
				long balance = vcoinWalletService.getBalance(user.getId());
				if(balance > 0) {
					vcoinWalletService.subtract(user.getId(), (int) balance, "CELEBRATE_DEPOSITORY_CLEAN", "2周年庆活动上线前积分清零");
				}
				CacheUtil.setAttribute("act.anniversary.20170807activity." + user.getId() + ".clean-act20170703-vcoin", "1", 25 * 24 * 60 * 60);
			}
			VcoinWalletDO vcoinWalletDO = vcoinWalletService.get(VcoinWalletDO.class, user.getId());
			long userVcoin = 0;
			if (vcoinWalletDO != null) {
				userVcoin = vcoinWalletDO.getBalance();
			}
			view.addObject("anniversaryVcoin", userVcoin);
			
			// 剩余邀请豆
			String currentInviteSoy = CacheUtil.getAttribute("act.anniversary.2017invitesoy." + user.getId());
			// 宝箱机会
			String currentOpenBoxChange = CacheUtil.getAttribute("act.anniversary.2017openboxchange." + user.getId());
			// 抽奖次数
			int lotteryDrawChange = 0;
			
			if(activity != null && activity.getBeginTime().before(new Date()) && activity.getEndTime().after(new Date())) {
				String isSendLotteryDrawChange = CacheUtil.getAttribute("act.anniversary.2017lotterydrawchance.sendchangeflag." + user.getId() + DateUtil.formatDate(new Date()));
				String currentLotteryDrawChance = CacheUtil.getAttribute("act.anniversary.2017lotterydrawchance." + user.getId());
				lotteryDrawChange = StringUtil.isEmpty(currentLotteryDrawChance) ? 0 : Integer.parseInt(currentLotteryDrawChance);
				if (isSendLotteryDrawChange == null || Integer.parseInt(isSendLotteryDrawChange) == 0) {
					lotteryDrawChange = lotteryDrawChange + 1;
					String end = String.format(DateUtil.formatDate(new Date(), "yyyy-MM-dd") + "%s", " 23:59:59");
					int sencodes = (int) ((DateUtil.parseDate(end, "yyyy-MM-dd HH:mm:ss").getTime()-new Date().getTime()) / 1000);
					CacheUtil.setAttribute("act.anniversary.2017lotterydrawchance.sendchangeflag." + user.getId() + DateUtil.formatDate(new Date()), "1", sencodes);
					int days = DateUtil.days(activity.getBeginTime(), activity.getEndTime());
					CacheUtil.setAttribute("act.anniversary.2017lotterydrawchance." + user.getId(), String.valueOf(lotteryDrawChange), days * 24 * 60 * 60);
				} 
			}
			
			view.addObject("anniversaryInviteTimesCount", currentInviteSoy==null ? 0 : currentInviteSoy);
			view.addObject("anniversaryOpenBoxChangeCount", currentOpenBoxChange==null ? 0: currentOpenBoxChange);
			view.addObject("anniversaryLotteryChangeCount", lotteryDrawChange);
			
			String uri = request.getRequestURI();
			uri = uri.substring(request.getContextPath().length());
			String link = GloabConstant.WEB_PATH + uri;
			if(StringUtil.isNotEmpty(request.getQueryString())) {
				link += "?" + request.getQueryString();
			}
			if (StringUtil.isEmpty(user.getInviteCode())) {
				// 生成邀请码
				user.setInviteCode(getRandomString());
			}
			if (StringUtil.isEmpty(user.getInviteQrCode()) && StringUtil.isNotEmpty(user.getInviteCode())) {
				File qrcodeDir = new File(GloabConstant.PIC_ROOT + "/invite/");
				if (!qrcodeDir.exists()) {
					qrcodeDir.mkdirs();
				}
				File qrCodeFile = new File(qrcodeDir, user.getId() + ".png");
				try {
					QRcodeUtil.make(GloabConstant.WEB_PATH + "/h5/regist_new.jsp?invite_code=" + user.getInviteCode()
							+"&mobile="+user.getMobile().toString().substring(0,3)+"****"+user.getMobile().toString().substring(7), qrCodeFile, 300, 300);
					user.setInviteQrCode("invite/" + user.getId() + ".png");
					picService.upload2Ftp(new FileInputStream(qrCodeFile), ftpDir+"invite/" + user.getId() + ".png");
					userService.updateSkipCheckOwner(user);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			WeiXinVO weiXinVO = new WeiXinVO();
			weiXinVO.setLink(link);
			LOG.info(String.format("【2周年庆上线活动】url=[%s]", "u." + weiXinVO.getLink()));
			weiXinVO = weiXinService.getWeiXinVO(weiXinVO);
			LOG.info(String.format("【2周年庆上线活动】url=[%s]", "u." + weiXinVO.getLink()));
			view.addObject("weiXinVO", weiXinVO);
			view.addObject("inviteCode", user.getInviteCode());
			
			view.addObject("is_noward", request.getParameter("is_noward"));
			// 我的礼品
			try {
				view.addObject("myActivityGiftList", slaveActivityJoinService.findActivityUserRewardList("20170814box", user.getId()));
			} catch (ParseException e) {
				LOG.error("进入2周年庆活动页面，查询我的礼品出现错误！" + e);
			}
		} catch (Exception e) {
			LOG.error("进入2周年庆活动页面，出现错误！" + e);
		}
		
		return view;
	}
	
	private String getRandomString() {
		String base = "0123456789";
		// 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		String inviteCode = sb.toString();
		List<UserDO> userDOList = userService.findListByInviteCode(inviteCode);
		if (userDOList != null && userDOList.size() > 0) {
			inviteCode = getRandomString();
		}
		return inviteCode;
	}
	
	/**
	 * 触发登录状态
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/anniverary_activity_login_status.htm")
	public String anniveraryActivityLoginStatus(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if(user == null) {
			json.put("loginStatus", 0);
		} else {
			json.put("loginStatus", 1);
		}
		return json.toJSONString();
	}
	
}
